package Netty_basic.echo;


import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.nio.charset.Charset;

public class echo_server {
    public static void main(String[] args) {
        start2();
    }
    public static void start1(){
        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf=(ByteBuf) msg;
                                System.out.println(byteBuf.toString(Charset.defaultCharset()));

                                ByteBuf buffer = ctx.alloc().buffer();
                                buffer.writeBytes(byteBuf);
                                ctx.writeAndFlush(buffer);

                            }
                        });
                    }
                })
                .bind(8080);
    }

    public static void start2(){
        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                String s=(String)msg;
                                System.out.println(s);
                                //向channel写入的时候，传入的应该是bytebuf对象，所以需要将字符串转换成bytebuf，而不是直接传入s.getbytes();
                                ByteBuf buffer = ctx.alloc().buffer();
                                buffer.writeBytes(s.getBytes());
                                ctx.channel().writeAndFlush(buffer);
                            }
                        });
                    }
                })
                .bind(8080);
    }
}
